package com.fhz.day005.fragment;

import androidx.databinding.BindingAdapter;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.fhz.day005.R;
import com.fhz.day005.adapter.FoodAdapter;
import com.fhz.day005.databinding.FoodFragmentBinding;
import com.fhz.day005.entity.Food;

import java.util.ArrayList;
import java.util.List;

public class FoodFragment extends Fragment implements FoodAdapter.MyClick {

    private FoodViewModel mViewModel;

    private FoodFragmentBinding binding;
    public static FoodFragment newInstance() {
        return new FoodFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
//        inflater.inflate(R.layout.food_fragment, container, false);
        binding = DataBindingUtil.inflate(inflater, R.layout.food_fragment, container, false);

        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //只能创建无参的vm .而有的vm.需要借助工厂对象.
        mViewModel = new ViewModelProvider(this,new FoodViewModelFactory()).get(FoodViewModel.class);

        binding.rv.setLayoutManager(new LinearLayoutManager(getActivity()));


        mViewModel.getFood();

        List<Food.Data> list = new ArrayList<>();
        //请求数据源
        FoodAdapter foodAdapter = new FoodAdapter(list,getActivity());

        foodAdapter.setClick(this);

        mViewModel.getFoodMutableLiveData().observe(getActivity(), new Observer<Food>() {
            @Override
            public void onChanged(Food food) {
                //把新数据放入到适配器中
                list.clear();
                list.addAll(food.getData());
                foodAdapter.notifyDataSetChanged();
            }
        });

        binding.rv.setAdapter(foodAdapter);

    }

    @Override
    public void click(int i) {
        Toast.makeText(getActivity(), ""+i,Toast.LENGTH_SHORT).show();
//        mViewModel.setFoodData();
    }

}